import {getPageTicket, getTokenByOpenId, getSiteConfig, checkAccessToken} from '@/apis';
import {EmptyUtil} from '@/utils/modules/EmptyUtil'
import {ReUtil} from "@/utils/modules/ReUtil";
import type wx from "weixin-js-sdk-ts";

export class WxmpUtil {

    static getAppId = async () => {


        const x = await uni.getStorageSync("WxmpAppId");
        if (EmptyUtil.isNotEmptyString(x)) return x
        const {data} = await getSiteConfig(false)
        if (EmptyUtil.isNotEmptyString(data?.wxmpAppId)) {
            uni.setStorageSync("WxmpAppId", data.wxmpAppId)
            uni.setStorageSync("AccessToken", data.accessToken)
            return data.wxmpAppId
        } else {
            console.error("公众号AppId获取失败")
        }


    }

    static wxAuthorize = async () => {

        const AccessToken = uni.getStorageSync("AccessToken")
        if (EmptyUtil.isNotEmptyString(AccessToken)) {
            const {code} = await checkAccessToken()
            if (code === 0) return
        }

        const appId = await WxmpUtil.getAppId();
        const hasCode = window.location.href.indexOf("code=");
        if (hasCode < 0) {
            WxmpUtil.jump(appId)
            return
        }


        const authCode = ReUtil.getQueryString(window.location.href, "code")
        if (EmptyUtil.isEmptyString(authCode)) {
            alert("code 获取失败")
            return
        }
        // @ts-ignore
        const {code, data} = await getTokenByOpenId(appId, authCode)
        if (code === 0) {
            uni.setStorageSync("AccessToken", data.accessToken)
            return
        }
        uni.showModal({
            title: '问题提示',
            content: '尚未绑定游戏账号 无法访问当前功能',
            confirmText: '下载试玩',

            success: (res) => {
                if (res.confirm) {
                    uni.navigateTo({url: '/pages/index/index'})
                }
            }

        })


    }


    static jump = (appId: string) => {

        const source = window.location.href
        const reLink = source.indexOf('?#') < 0 ? source.replace('#', '?#') : source
        let uri = encodeURIComponent(reLink);
        const x = `https://open.weixin.qq.com/connect/oauth2/` +
            `authorize?appid=${appId}&redirect_uri=${uri}&response_type=code` +
            `&scope=snsapi_userinfo&connect_redirect=1#wechat_redirect`;
        window.location.replace(x)
        return
    }

    static getWxConfigData = async (jsApiList: wx.jsApiList) => {
        const appId = await WxmpUtil.getAppId();
        const body = {appId, url: window.location.href}
        let {data} = await getPageTicket(body);
        return {...data, jsApiList, debug: false}

    }


}
